package com.yu.mall.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class PasswordUtil {

    public static final String KEY = "xUHdKxzVCbsgVIwTnc1jtpsdfsdfn";

    public static byte[] hex(String key){
        String f = DigestUtils.md5Hex(key);
        byte[] bkeys = new String(f).getBytes();
        byte[] enk = new byte[24];
        for (int i=0;i<24;i++){
            enk[i] = bkeys[i];
        }
        return enk;
    }

    public static String  encode3Des(String key,String srcStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] keybyte = hex(key);
        byte[] src = srcStr.getBytes();
        //生成密钥
        SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
        //加密
        Cipher c1 = Cipher.getInstance("DESede");
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        String pwd = Base64.encodeBase64String(c1.doFinal(src));
        return pwd;
    }

    public static String decode3Des(String key, String desStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Base64 base64 = new Base64();
        byte[] keybyte = hex(key);
        byte[] src = base64.decode(desStr);

        //生成密钥
        SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
        //解密
        Cipher c1 = Cipher.getInstance("DESede");
        c1.init(Cipher.DECRYPT_MODE, deskey);
        String pwd = new String(c1.doFinal(src));
        return pwd;
    }

}
